package com.fly.simple;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Collections;
import java.util.List;
import java.util.ResourceBundle;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.SystemUtils;

import com.fly.simple.entity.Article;
import com.fly.simple.entity.BlogData;
import com.fly.simple.entity.Record;
import com.fly.simple.utils.JsonBeanUtils;
import com.fly.simple.utils.ShellExecutor;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class JsonDataWrite
{
    /**
     * webApi获取接口数据->写入结果文件
     * 
     * @param args
     * @throws IOException
     */
    public static void main(String[] args)
        throws IOException
    {
        // windows下Jar运行返回值中文乱码，unix下Jar运行返回值正常
        List<Article> articles = IntStream.rangeClosed(1, 2)
            .mapToObj(i -> String.format("curl -e \"blog.csdn.net\" \"https://blog.csdn.net/community/home-api/v1/get-business-list?page=%s&size=100&businessType=blog&username=qq_16127313\"", i))
            .map(cmd -> ShellExecutor.execute(cmd))
            .map(json -> parseToArticles(json))
            .flatMap(List::stream)
            .collect(Collectors.toList());
        
        // 构造对象
        BlogData blogData = new BlogData().setData(new Record().setList(articles));
        
        // 写入结果文件
        File out = new File(ResourceBundle.getBundle("config").getString("out"));
        FileUtils.writeStringToFile(out, JsonBeanUtils.beanToJson(blogData, true), Charset.defaultCharset(), false);
        if (SystemUtils.IS_OS_WINDOWS)
        {
            ShellExecutor.exec("start " + out.getParent());
        }
    }
    
    /**
     * 解析json为List
     * 
     * @param json
     * @return
     */
    private static List<Article> parseToArticles(String json)
    {
        try
        {
            if (SystemUtils.IS_OS_WINDOWS)
            {
                log.info("json:\n {}", json);
            }
            return JsonBeanUtils.jsonToBean(json, BlogData.class, true).getData().getList();
        }
        catch (IOException e)
        {
            log.error(e.getMessage(), e);
            return Collections.emptyList();
        }
    }
}
